<template>
  <div class="demo">
    <div class="demo-title">useForm 合并错误信息</div>
    <div class="demo-content">
      <Form :label-col="labelCol" :wrapper-col="wrapperCol">
        <Form.Item label="Activity name" required>
          <Input v-model:value="modelRef.name" />
        </Form.Item>
        <Form.Item label="Activity zone" required>
          <Select v-model:value="modelRef.region" placeholder="please select your zone">
            <Select.Option value="shanghai">Zone one</Select.Option>
            <Select.Option value="beijing">Zone two</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="Activity type" required>
          <Checkbox.Group v-model:value="modelRef.type">
            <Checkbox value="1" name="type">Online</Checkbox>
            <Checkbox value="2" name="type">Promotion</Checkbox>
            <Checkbox value="3" name="type">Offline</Checkbox>
          </Checkbox.Group>
        </Form.Item>
        <Form.Item class="error-infos" :wrapper-col="{ span: 14, offset: 4 }" v-bind="errorInfos">
          <Button type="primary" @click.prevent="onSubmit">Create</Button>
          <Button style="margin-left: 10px" @click="resetFields">Reset</Button>
        </Form.Item>
      </Form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, toRaw, computed } from 'vue';
  import { toArray } from 'lodash-es';
  import Button from '@sscd/button';
  import Input from '@sscd/input';
  import Select from '@sscd/select';
  import Checkbox from '@sscd/checkbox';
  import Form from '@sscd/form';
  const labelCol = { span: 4 };
  const wrapperCol = { span: 14 };
  const modelRef = reactive({ name: '', region: undefined, type: [] });
  const rulesRef = reactive({
    name: [{ required: true, message: 'Please input name' }],
    region: [{ required: true, message: 'Please select region' }],
    type: [{ required: true, message: 'Please select type', type: 'array' }],
  });
  const { resetFields, validate, validateInfos, mergeValidateInfo } = Form.useForm(
    modelRef,
    rulesRef
  );
  const onSubmit = () => {
    validate()
      .then(() => console.log(toRaw(modelRef)))
      .catch((err) => console.log('error', err));
  };
  const errorInfos = computed(() => {
    return mergeValidateInfo(toArray(validateInfos));
  });
</script>
